<template>
  <div class="visits-page">
    <!-- 固定的顶部header -->
    <div class="header">
      <button class="back-btn" @click="goBack">
        ← 返回列表
      </button>
      <div class="header-title">
        <h1>钓鱼收获记录</h1>
        <p>这里显示钓点的钓鱼收获记录和详情</p>
      </div>
    </div>
    
    <div class="scrollable-content">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>正在加载收获记录...</p>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="error-container">
        <div class="error-icon">⚠️</div>
        <p>{{ error }}</p>
        <button @click="loadVisits" class="retry-btn">重试</button>
      </div>

      <!-- 空状态 -->
      <div v-else-if="harvests.length === 0" class="empty-container">
        <div class="empty-icon">🎣</div>
        <h3>暂无收获记录</h3>
        <p>当前钓点还没有钓鱼收获记录</p>
      </div>

      <!-- 收获记录表格 -->
      <div v-else class="harvests-table-container">
        <table class="harvests-table">
          <thead>
            <tr>
              <th>用户信息</th>
              <th>垂钓时间</th>
              <th>收获鱼种</th>
              <th>收获类型</th>
              <th>评分</th>
              <th>推荐</th>
              <th>收获图片</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="harvest in harvests" :key="harvest.id">
              <td class="user-info-cell">
                <div class="table-user-info">
                  <img 
                    v-if="harvest.avatarUrl" 
                    :src="harvest.avatarUrl" 
                    class="table-user-avatar"
                    alt="用户头像"
                  />
                  <span class="table-user-name">{{ harvest.nickName || '匿名钓友' }}</span>
                </div>
              </td>
              <td>{{ formatDate(harvest.fishingAt) }}</td>
              <td>
                <div class="table-fish-tags">
                  <span 
                    v-for="fish in harvest.fishes" 
                    :key="fish.code"
                    class="fish-tag"
                  >
                    {{ fish.name }}
                  </span>
                </div>
              </td>
              <td>{{ harvest.harvestTypeVal.name }}</td>
              <td>
                <span class="score-badge" :class="getScoreClass(harvest.score)">
                  {{ harvest.scoreVal.name }}
                </span>
              </td>
              <td>
                <span v-if="harvest.isRec === 1" class="rec-badge">推荐</span>
                <span v-else>-</span>
              </td>
              <td>
                <div v-if="harvest.jsonHisPictures && harvest.jsonHisPictures.length > 0" class="table-harvest-images">
                  <img 
                    v-for="(img, index) in harvest.jsonHisPictures.slice(0, 3)" 
                    :key="index"
                    :src="img" 
                    class="harvest-image"
                    alt="钓鱼收获"
                  />
                </div>
                <span v-else>-</span>
              </td>
            </tr>
          </tbody>
        </table>

        <!-- 加载更多 -->
        <div v-if="hasMore" class="load-more-container">
          <button @click="loadMore" :disabled="loadingMore" class="load-more-btn">
            {{ loadingMore ? '加载中...' : '加载更多' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { invoke } from '@tauri-apps/api/core'

interface Fish {
  code: string
  type: number
  name: string
}

interface ScoreVal {
  code: string
  type: number
  name: string
}

interface HarvestTypeVal {
  code: string
  type: number
  name: string
}

interface Harvest {
  id: string
  spotId: string
  fisherId: string
  fishes: Fish[]
  harvestType: string
  harvestTypeVal: HarvestTypeVal
  isRec: number
  score: number
  scoreVal: ScoreVal
  fishingAt: string
  jsonHisPictures: string[]
  avatarUrl: string
  nickName: string
}

interface ApiResponse {
  status: number
  msg: string
  data: {
    records: Harvest[]
    current: number
    pages: number
    total: number
  }
}

// 路由和状态管理
const router = useRouter()
const harvests = ref<Harvest[]>([])
const loading = ref(false)
const loadingMore = ref(false)
const error = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const hasMore = ref(true)
const spotId = ref('') // 从路由参数获取spotId

// 获取路由参数
import { useRoute } from 'vue-router'
const route = useRoute()

// 页面加载时获取数据
onMounted(() => {
  spotId.value = route.query.spotId as string || route.params.spotId as string || ''
  loadVisits()
})

// 加载收获记录
const loadVisits = async () => {
  if (!spotId.value) {
    error.value = '请选择钓点'
    return
  }

  try {
    loading.value = true
    error.value = ''
    
    const response = await invoke('get_spot_harvests', {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      spotId: spotId.value
    })
    
    // 添加日志以调试响应结构
    console.log('API Response:', response)
    
    // 检查响应结构并适配
    if (typeof response === 'object' && response !== null) {
      // 适配两种可能的响应格式
      if ('status' in response) {
        // 格式1: { status, msg, data: { records, pages } }
        const statusResponse = response as { status: number; msg?: string; data?: { records?: Harvest[]; pages?: number } }
        if (statusResponse.status === 1) {
          harvests.value = statusResponse.data?.records || []
          hasMore.value = currentPage.value < (statusResponse.data?.pages || 0)
        } else {
          error.value = statusResponse.msg || '加载收获记录失败'
        }
      } else if ('records' in response) {
        // 格式2: { records, pages, total, ... }
        const recordsResponse = response as { records?: Harvest[]; pages?: number }
        harvests.value = recordsResponse.records || []
        hasMore.value = currentPage.value < (recordsResponse.pages || 0)
      } else {
        error.value = '无效的响应格式'
      }
    } else {
      error.value = '无效的响应'
    }
  } catch (err) {
    console.error('API调用错误:', err)
    error.value = '加载失败：' + (err as Error).message
  } finally {
    loading.value = false
  }
}

// 加载更多
const loadMore = async () => {
  if (loadingMore.value || !hasMore.value || !spotId.value) return
  
  try {
    loadingMore.value = true
    currentPage.value++
    
    const response = await invoke('get_spot_harvests', {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      spotId: spotId.value
    })
    
    // 添加日志以调试响应结构
    console.log('Load More API Response:', response)
    
    // 检查响应结构并适配
    if (typeof response === 'object' && response !== null) {
      // 适配两种可能的响应格式
      if ('status' in response) {
        // 格式1: { status, msg, data: { records, pages } }
        const statusResponse = response as { status: number; msg?: string; data?: { records?: Harvest[]; pages?: number } }
        if (statusResponse.status === 1) {
          if (statusResponse.data?.records && Array.isArray(statusResponse.data.records)) {
            harvests.value.push(...statusResponse.data.records)
            hasMore.value = currentPage.value < (statusResponse.data?.pages || 0)
          }
        } else {
          // 加载更多失败时回退页面
          currentPage.value--
          console.warn('加载更多失败:', statusResponse.msg)
        }
      } else if ('records' in response) {
        // 格式2: { records, pages, total, ... }
        const recordsResponse = response as { records?: Harvest[]; pages?: number }
        if (recordsResponse.records && Array.isArray(recordsResponse.records)) {
          harvests.value.push(...recordsResponse.records)
          hasMore.value = currentPage.value < (recordsResponse.pages || 0)
        }
      } else {
        // 加载更多失败时回退页面
        currentPage.value--
        console.warn('无效的响应格式')
      }
    } else {
      // 加载更多失败时回退页面
      currentPage.value--
      console.warn('无效的响应')
    }
  } catch (err) {
    // 加载更多失败时回退页面
    currentPage.value--
    console.error('加载更多失败:', err)
  } finally {
    loadingMore.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 日期格式化
const formatDate = (dateString: string) => {
  if (!dateString) return '未知时间'
  
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch {
    return dateString
  }
}

const getScoreClass = (score: number) => {
  switch(score) {
    case 1: return 'score-1'
    case 2: return 'score-2'
    case 3: return 'score-3'
    case 4: return 'score-4'
    case 5: return 'score-5'
    default: return 'score-default'
  }
}
</script>

<style scoped>
/* 主要页面容器样式（从FavoritesPage复制） */
.visits-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  color: #ffffff;
  background: #1e1e1e;
  overflow: hidden;
}

.header {
  position: sticky;
  top: 0;
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 16px 24px;
  background: rgba(30, 30, 35, 0.95);
  backdrop-filter: blur(12px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  z-index: 100;
  flex-shrink: 0;
}

.back-btn {
  background: rgba(29, 185, 84, 0.2);
  color: #1db954;
  border: 1px solid #1db954;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.back-btn:hover {
  background: rgba(29, 185, 84, 0.3);
}

.header-title {
  flex: 1;
  text-align: center;
}

.header-title h1 {
  font-size: 20px;
  font-weight: 600;
  color: #ffffff;
  margin: 0 0 4px 0;
}

.header-title p {
  font-size: 14px;
  color: #b3b3b3;
  margin: 0;
}

.scrollable-content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

/* 加载、错误、空状态样式（从FavoritesPage复制） */
.loading-container,
.error-container,
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #b3b3b3;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(29, 185, 84, 0.3);
  border-top: 3px solid #1db954;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-icon,
.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.error-container p,
.empty-container p {
  color: #b3b3b3;
  font-size: 16px;
  margin-bottom: 16px;
}

.retry-btn {
  background: rgba(29, 185, 84, 0.2);
  color: #1db954;
  border: 1px solid #1db954;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  margin-top: 16px;
}

.retry-btn:hover {
  background: rgba(29, 185, 84, 0.3);
}



/* 收获记录表容器 */
.harvests-table-container {
  width: 100%;
  margin: 0 auto;
  overflow-y: auto;
  overflow-x: auto;
  min-height: 400px;
  padding-bottom: 20px;
}

/* 收获记录表样式 */
.harvests-table {
  width: 100%;
  border-collapse: collapse;
  background: rgba(40, 40, 45, 0.8);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  overflow: hidden;
}

/* 表头样式 */
.harvests-table th {
  background: rgba(30, 30, 35, 0.95);
  color: #ffffff;
  font-weight: 600;
  text-align: left;
  padding: 16px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  font-size: 14px;
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: 0 2px 2px -1px rgba(0, 0, 0, 0.1);
}

/* 表格内容样式 */
.harvests-table td {
  padding: 16px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);
  vertical-align: top;
  color: #cccccc;
}

/* 表格行悬停效果 */
.harvests-table tbody tr:hover {
  background: rgba(45, 45, 50, 0.9);
}

/* 表格中用户信息 */
.table-user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid rgba(29, 185, 84, 0.3);
}

.table-user-name {
  font-weight: 600;
  color: #ffffff;
  font-size: 14px;
}

/* 表格中鱼种标签 */
.table-fish-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.fish-tag {
  background: rgba(29, 185, 84, 0.2);
  color: #1db954;
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 12px;
  border: 1px solid rgba(29, 185, 84, 0.3);
}

/* 评分徽章样式 */
.score-badge {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.score-1 { background: rgba(248, 215, 218, 0.2); color: #f8d7da; border-color: rgba(248, 215, 218, 0.3); }
.score-2 { background: rgba(255, 243, 205, 0.2); color: #fff3cd; border-color: rgba(255, 243, 205, 0.3); }
.score-3 { background: rgba(209, 236, 241, 0.2); color: #d1ecf1; border-color: rgba(209, 236, 241, 0.3); }
.score-4 { background: rgba(212, 237, 218, 0.2); color: #d4edda; border-color: rgba(212, 237, 218, 0.3); }
.score-5 { background: rgba(40, 167, 69, 0.2); color: #28a745; border-color: rgba(40, 167, 69, 0.3); }
.score-default { background: rgba(233, 236, 239, 0.2); color: #e9ecef; border-color: rgba(233, 236, 239, 0.3); }

/* 推荐徽章样式 */
.rec-badge {
  background: rgba(255, 107, 107, 0.2);
  color: #ff6b6b;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
  border: 1px solid rgba(255, 107, 107, 0.3);
}

/* 表格中收获图片 */
.table-harvest-images {
  display: flex;
  gap: 8px;
}

.harvest-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

/* 加载更多 */
.load-more-container {
  text-align: center;
  margin-top: 24px;
}

.load-more-btn {
  background: rgba(29, 185, 84, 0.2);
  color: #1db954;
  border: 1px solid #1db954;
  padding: 12px 32px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.load-more-btn:hover:not(:disabled) {
  background: rgba(29, 185, 84, 0.3);
}

.load-more-btn:disabled {
  background: rgba(255, 255, 255, 0.1);
  color: #b3b3b3;
  border-color: rgba(255, 255, 255, 0.2);
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .scrollable-content {
    padding: 16px;
  }
  
  .harvests-table {
    font-size: 12px;
  }
  
  .harvests-table th,
  .harvests-table td {
    padding: 12px 8px;
  }
  
  .table-user-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
  }
  
  .table-user-avatar {
    width: 30px;
    height: 30px;
  }
  
  .harvest-image {
    width: 50px;
    height: 50px;
  }
}

@media (max-width: 480px) {
  .harvests-table {
    font-size: 11px;
  }
  
  .harvests-table th,
  .harvests-table td {
    padding: 8px 4px;
  }
  
  .table-fish-tags {
    flex-direction: column;
    gap: 4px;
  }
  
  .fish-tag {
    font-size: 11px;
    padding: 2px 8px;
  }
}
</style>